<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function index(){

        return view('admin/login');
    }

    public function login(Request $Request){

        $data = $Request->input();

        $validator = \Validator::make($data,
        [   'username'     => 'bail|required|alpha_dash|between:4,30',
            'password'     => 'bail|required|alpha_dash|between:4,30',
            ],
        [   'required'     => ':attribute 不能为空' ,
            'alpha_dash'   => ':attribute 必须为数字或字母',
            'between'      => ':attribute 为4~30位字母跟数字',
            ],
        [   'username'     => '用户名',
            'password'     => '密码',
        ]);

        if($validator->fails()){
            $msg = $validator->errors();
            return $msg->first();
        }

        $user = DB::table('admin')->where('username',$data['username'])->where('password',md5($data['password'].config('app.salt')))->value('password');

        if($user){
            Redis::set('username',$data['username']);

            return ['status'=>0,'msg'=>'登录成功'];
        }else{
            return '账号或密码错误';
        }
    }
}
